package com.cdream.basic.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import okhttp3.*;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class ImageUtilExample {

    /**
     * 将oss的发票图片传递到腾讯云
     *
     * @param url
     * @return
     */
    public static String uploadImg(String url) throws IOException {
        File file = FileUtil.file("https://drp2.oss-cn-shanghai.aliyuncs.com/attachment/EI0000001.pdf");
        Map<String, Object> body = MapUtil.<String, Object>builder().put("fileName", "fileName")
                .put("fileType", "application/pdf").put(
                        "fileSize", file.length()).build();
        HttpResponse response = HttpRequest.post("https://api.qidian.qq.com/cgi-bin/b2b/api/salesOrders/attachments/upload?access_token=YzdlZjc0ZjUxNWI0ZTFkOGEwZmQ5OGY4ZGQ5ZWJlMzYxOWU1MWE5YiZ0PTE1OTQ3MTA2JmE9NTAwMDAwMDgyJnU9MjM0MjA2Mjk4OTI3ODUzNTY4JnM9MTMwMDAwMDE4NiZJPTE")
                .header("Content-Type", "application/pdf")
                .form("file", file)
                .body(JSONUtil.toJsonStr(body)).execute();

        return response.body();
    }

    /**
     * 根据图片链接转为base64数据
     *
     * @param imageUrl
     * @return
     * @throws Exception
     */
    public static String getBase64ByUrl(String imageUrl) throws Exception {
        // new一个URL对象
        URL url = new URL(imageUrl);
        // 打开链接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        // 设置请求方式为"GET"
        conn.setRequestMethod("GET");
        // 超时响应时间为5秒
        conn.setConnectTimeout(5 * 1000);
        // 通过输入流获取图片数据
        InputStream inStream = conn.getInputStream();
        // 得到图片的二进制数据，以二进制封装得到数据，具有通用性
        byte[] data = readInputStream(inStream);
        String s = Base64.encode(data);
        return s;
    }

    private static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        // 创建一个Buffer字符串
        byte[] buffer = new byte[1024];
        // 每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len = 0;
        // 使用一个输入流从buffer里把数据读取出来
        while ((len = inStream.read(buffer)) != -1) {
            // 用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        // 关闭输入流
        inStream.close();
        // 把outStream里的数据写入内存
        return outStream.toByteArray();
    }

    /**
     * 测试
     */
    public static void main(String[] args) {
        File file = getFileByUrl();
        // String url = "https://api.qidian.qq.com/cgi-bin/b2b/api/salesOrders/attachments/upload?access_token=Mzc4YTg0ZWQxOGZiZjFkMzkzZDkzMTdhYzAzMWU2MzQ0ZWFkMDU3NyZ0PTE1OTQ4Njk0JmE9NTAwMDAwMDgyJnU9MjM0MjA2Mjk4OTI3ODUzNTY4JnM9MTMwMDAwMDE4NiZJPTE";
        String url = "https://qidian-kylin-1251316161.cos.ap-guangzhou.myqcloud.com/234206298927853568/-1/1594876914022-6a0fb73b-0dc7-4f72-a51c-1ca1f0ef5698.pdf";
        MediaType mediaType = MediaType.parse("application%2Fpdf");
        RequestBody fileBody = RequestBody.create(mediaType, file);
        Request request = new Request.Builder()
                .url(url)
                .method("PUT", fileBody)
                .addHeader("Authorization", "q-sign-algorithm=sha1&q-ak=AKID77wZ5RpfV9brvnpzJSOCsPkutkPsIF9s&q-sign-time=1594876914;1595476914&q-key-time=1594876914;1595476914&q-header-list=content-type&q-url-param-list=&q-signature=1cc88432f7460bb5a562a70bb22587cc3830d82a")
                .addHeader("Content-Type", "application%2Fpdf")
                .build();
        OkHttpClient client = new OkHttpClient.Builder().readTimeout(3, TimeUnit.MINUTES).build();
        try {
            Response response = client.newCall(request).execute();
            System.out.println(response.isSuccessful());
        } catch (
                IOException e) {
            e.printStackTrace();
        }
    }

    private static File getFileByUrl() {
        try {
            String destUrl = "https://drp2.oss-cn-shanghai.aliyuncs.com/attachment/EI0000001.pdf";
            HttpURLConnection httpUrl = (HttpURLConnection) new URL(destUrl).openConnection();
            httpUrl.connect();
            File file = inputStreamToFile(httpUrl.getInputStream(), StrUtil.subAfter(destUrl,"/",true));

            httpUrl.disconnect();
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 工具类
     * inputStream 转 File
     */
    public static File inputStreamToFile(InputStream ins, String name) throws Exception {
        File file = new File(System.getProperty("java.io.tmpdir") + File.separator + name);
        if (file.exists()) {
            return file;
        }
        OutputStream os = new FileOutputStream(file);
        int bytesRead;
        int len = 8192;
        byte[] buffer = new byte[len];
        while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        ins.close();
        return file;
    }

}
